package com.ccp.dev.workflow.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.annotion.ActionExecOrder;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.*;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.system.model.GlobalType;
import com.ccp.dev.system.service.GlobalTypeService;
import com.ccp.dev.workflow.model.*;
import com.ccp.dev.workflow.service.*;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassDescribe:常用语管理 控制器
 * @author :fanruiqi
 * Date: 2019-09-09
 */
@Controller
@RequestMapping(UrlConstants.PROJECT_ROOT + UrlConstants.PROJECT_MODULE_WORKFLOW + "/taskApprovalItems")
@Action(ownermodel = SysAuditModelType.PROCESS_MANAGEMENT)
public class TaskApprovalItemsController extends SysBaseController {
    private static final Logger logger = LoggerFactory.getLogger(TaskApprovalItemsService.class);


    @Resource
    private ActDefModelService actDefModelService;
    @Resource
    private GlobalTypeService globalTypeService;
    @Resource
    private TaskApprovalItemsService taskApprovalItemsService;

    /**
     * 跳转常用语设置页面
     * @param request
     * @param model
     * @return 跳转页面
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX+UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description = "常用语设置列表页面跳转",exectype = "页面跳转日志")
    public String viewList(HttpServletRequest request,Model model){
        //用于判断常用语设置的具体模块，若是流程管理模块isAdmin=true，否则个人办公模块isAdmin=false
        Boolean isAdmin = RequestUtil.getBoolean(request,"isAdmin",false);
        //获取当前用户，判断是不是超级管理员账号，若是则常用语设置有第二个查询条件，否则没有
        String currUserId = RequestUtil.getString(request,"currUserId");
        model.addAttribute("isAdmin", isAdmin)
             .addAttribute("currUserId",currUserId);
        return getAutoView();
    }

    /**
     * 跳转添加页面
     * @param request
     * @param model
     * @return 跳转页面
     * 2019-11-11  常用语无需编辑回显功能，故删除编辑回显的相关功能代码
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX+"/edit")
    @Action(description = "常用语添加页面跳转",exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request,Model model){
        Boolean isAdmin = RequestUtil.getBoolean(request,"isAdmin",false);
        model.addAttribute("isAdmin",isAdmin);
        return getAutoView();
    }

    /**
     * 查询常用语设置页面列表数据
     * @param request
     * @return 返回数据
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description = "常用语设置列表数据查询",detail = "常用语设置列表数据查询成功")
    @ResponseBody
    public ResultData getList(HttpServletRequest request) {
        QueryFilter queryFilter = new QueryFilter(request);
        String userId = ContextUtil.getCurrentUserId();
        queryFilter.addFilter("userId",userId);
        List<TaskApprovalItems> list = taskApprovalItemsService.queryList(queryFilter);


        //保存流程为map，键为流程的modelKey，值为name(老平台为subject)
        Map<String, String> modelMap = new HashMap<String, String>();
        Map<String, String> modelTempMap = new HashMap<String, String>();
        //保存流程分类为map，键为流程分类的Id，值为TypeName
        Map<String, String> modelTypeMap = new HashMap<String, String>();
        Map<String, String> modelTypeTempMap = new HashMap<String, String>();

        //获取所有的最新版流程
        // 2019-11-06   修改传参为null，不加任何条件约束获取所有的流程数据，解决当流程非当前用户所创时常用语设置无法正常显示作用对象的问题
        List<ActDefModel> actDefModelList = actDefModelService.queryList(null);
        for(ActDefModel actDefModel:actDefModelList){
            modelTempMap.put(actDefModel.getModelKey(),actDefModel.getName());
        }
        //获取所有的流程分类，处理流程分类
        List<GlobalType> globalTypeList = globalTypeService.getByCatKey(GlobalType.CAT_FLOW, false);
        for(GlobalType globalType:globalTypeList){
            modelTypeTempMap.put(globalType.getTypeId(),globalType.getTypeName());
        }

        for(TaskApprovalItems item:list){
            if(item.getType().equals(TaskApprovalItems.TYPE_FLOW)){
                modelMap.put(item.getModelKey(),modelTempMap.get(item.getModelKey()));
            }
            else if(item.getType().equals(TaskApprovalItems.TYPE_FLOWTYPE)){
                modelTypeMap.put(item.getTypeId(),modelTypeTempMap.get(item.getTypeId()));
            }
        }
        Map<String,Object> map = new HashMap<String,Object>(6);
        map.put("taskApprovalList",list);
        map.put("modelMap",modelMap);
        map.put("modelTypeMap",modelTypeMap);
        map.put("globalTypeList",globalTypeList);
        JSONObject jsonObject = JSONObject.fromObject(map);
        return getResultDataSuccess("query.success",queryFilter.getPageBean().getTotalCount(),jsonObject);
    }


    /**
     *  保存常用语设置
     * @param request
     * @return 返回结果
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @Action(description = "保存常用语设置",
    detail = "常用语设置<#if add>添加成功<elseif update>更新成功<#else>添加失败</#if>")
    @ResponseBody
    public ResultData save(HttpServletRequest request){
        String tenantId = ContextUtil.getCurrentUser().getTenantId();
        String userId   = ContextUtil.getCurrentUser().getUserId();
        String itemId   = RequestUtil.getString(request, "itemId");
        Short  type     = RequestUtil.getShort(request, "type", (short) 1);
        String approvalItem = RequestUtil.getString(request, "approvalItem");
        String typeId   = RequestUtil.getString(request, "flowTypeId");
        String modelKey   = RequestUtil.getString(request, "modelKey");
        List list = taskApprovalItemsService.getByExpression(approvalItem, itemId);
        int number = list.size();
        try{
            if(number >0 ){
                return getResultDataError("taskApproval.save.failure");
            }else{
                if(StringUtil.isEmpty(itemId)){
                    String msg = taskApprovalItemsService.addTaskApproval(approvalItem, type, typeId, modelKey, ContextUtil.getCurrentUserId());
                    if(StringUtil.isEmpty(msg)) {
                        SysAuditThreadLocalHolder.putParamerter("add",true);
                        return getResultDataSuccess("taskApproval.add.success");
                    }else{
                        SysAuditThreadLocalHolder.putParamerter("add",false);
                        return getResultDataError(msg);
                    }
                }else {
                    TaskApprovalItems taskApprovalItems = new TaskApprovalItems();
                    taskApprovalItems.setTenantId(tenantId);
                    taskApprovalItems.setItemId(itemId);
                    taskApprovalItems.setExpression(approvalItem);
                    taskApprovalItems.setType(type);
                    taskApprovalItems.setUserId(userId);
                    taskApprovalItemsService.update(taskApprovalItems);
                    SysAuditThreadLocalHolder.putParamerter("update",true);
                    return getResultDataSuccess("taskApproval.update.success");
                }
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 删除常用语设置
     * @param request
     * @return 返回结果
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @Action(description = "删除常用语",
            execOrder = ActionExecOrder.BEFORE,
            detail = "<#if success>删除成功</#if>")
    @ResponseBody
    public ResultData del(HttpServletRequest request){
        String[] ids = RequestUtil.getStringAryByStr(request,"ids");
        try {
            taskApprovalItemsService.delByIdArray(ids);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("delete.success");
        } catch (Exception e) {
            logger.error(e.getMessage());
            return getResultDataError("delete.failure");
        }
    }

}